package com.bnyy.medicalHousekeeper.moudle.message.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bnyy.common.adapter.BaseNormalListAdapter;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.UserInfoManager;
import com.bnyy.medicalHousekeeper.moudle.message.ChatManager;
import com.bnyy.medicalHousekeeper.moudle.message.MessageHeaderHelper;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.chat.Chat;
import com.bnyy.message.bean.chat.ChatInfo;
import com.bnyy.message.bean.chat.ChatMessage;
import com.bnyy.message.enums.ChatMessageStatus;
import com.bnyy.message.enums.ChatType;
import com.bnyy.message.enums.MessageType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/6/30
 **/
public class ChatAdapter extends BaseNormalListAdapter<Chat, ChatAdapter.ViewHolder> {

    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    private Callback callback;

    public ChatAdapter(Context context, Callback callback) {
        super(context);
        this.callback = callback;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_chat, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);

        holder.swipeMenuLayout.quickClose();
        holder.tvContent.setTextColor(ContextCompat.getColor(mContext, R.color.gray_light));
        holder.tvTime.setText("");
        holder.tvContent.setText("");
        holder.tvUnreadCount.setVisibility(View.GONE);
        holder.ivNoDisturb.setVisibility(View.GONE);
        Chat chat = getData(position);

        Log.e("chatItem", "chat = " + new Gson().toJson(chat));

        if (chat.getToppingTime() > 0) {
            holder.rlRoot.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gray_FA));
        } else {
            holder.rlRoot.setBackgroundColor(Color.WHITE);
        }

        ChatType chatType = chat.getChatType();

        if (chatType != null) {

            ChatMessage chatMessage = MessageManager.getLatestChatMessage(chatType);
            Log.e("chatItem", "chatMessage = " + new Gson().toJson(chatMessage));
            int unreadCount = MessageManager.getUnreadCount(chat);

            if (unreadCount > 0) {
                holder.tvUnreadCount.setVisibility(View.VISIBLE);
                if (unreadCount > 99) {
                    holder.tvUnreadCount.setText("99+");
                } else {
                    holder.tvUnreadCount.setText(unreadCount + "");
                }
            }

            switch (chatType) {
                case GROUP_CHAT:
                case PRIVATE_CHAT:
                    holder.swipeMenuLayout.setSwipeEnable(true);
                    String content = "";

                    if (chatMessage != null) {
                        MessageType messageType = chatMessage.getMessageType();
                        switch (messageType) {
                            case CHAT_TEXT:
                                content += chatMessage.getContent();
                                break;
                            case CHAT_IMAGE:
                                content = "[图片]";
                                break;
                            case CHAT_AUDIO:
                                content = "[语音]";
                                if (!chatMessage.isPlayed()) {
                                    holder.tvContent.setTextColor(Color.RED);
                                }
                                break;
                            case MALL_GOODS: // 商城商品
                            case SERVICE_GOODS: // 服务商品
                            case HEALTH_ALERT: // 健康警报
                            case HEALTH_WEEKLY: // 健康周报
                            case ALARM: // 救援
                            case FENCE: // 电子围栏
                            case GROUP_CHAT_INVITATION: // 邀请加入群聊
                            case USER_HOMEPAGE: // 分享个人主页
                            case GROUP_CHAT_VOTE:
                            case GROUP_CHAT_ACTIVITY:
                            case ARTICLE:
                                content = "[" + messageType.getName() + "]";
                                break;
                            case GROUP_CHAT_NOTICE:
                                content = "群公告：" + chatMessage.getContent();
                                break;
                            default:
                                content = chatMessage.getContent();
                                break;
                        }
                        if (!TextUtils.isEmpty(content)) {
                            if (chatType == ChatType.GROUP_CHAT) {
                                if (messageType.isTipsChatMessage()) {
                                    holder.tvContent.setText(content);
                                } else {
                                    int loginUserId = UserInfoManager.getInstance().getLoginUserId();
                                    String atIds = chatMessage.getAtIds();
                                    Log.e(chat.getChatId(), "atIds = " + atIds);
                                    if (!TextUtils.isEmpty(atIds)) {
                                        Log.e(chat.getChatId(), Arrays.toString(atIds.split("\\|")));
                                        Optional<String> first = Arrays.stream(atIds.split("\\|"))
                                                .filter(new Predicate<String>() {
                                                    @Override
                                                    public boolean test(String s) {
                                                        Log.e(chat.getChatId(), "s = " + s);
                                                        return s.equals(String.valueOf(loginUserId));
                                                    }
                                                }).findFirst();

                                        if (first.isPresent()) {
                                            SpanUtils spanUtils = SpanUtils.with(holder.tvContent)
                                                    .append("[有人@你]");
                                            if (!chatMessage.isRead()) {
                                                spanUtils.setForegroundColor(Color.RED);
                                            }
                                            spanUtils.append(content).create();
                                        } else {
                                            holder.tvContent.setText(chatMessage.getUsername() + "：" + content);
                                        }
                                    } else {
                                        holder.tvContent.setText(chatMessage.getUsername() + "：" + content);
                                    }
                                }
                            } else {
                                holder.tvContent.setText(content);
                            }
                        }

                        if (chatMessage.getChatMessageStatus() == ChatMessageStatus.FAILURE) {
                            holder.ivSendFailure.setVisibility(View.VISIBLE);
                        } else {
                            holder.ivSendFailure.setVisibility(View.GONE);
                        }
                    }

                    ChatInfo chatInfo = chat.getChatInfo();
                    if (chatInfo != null) {
                        if (chat.getRecipientRoleId() == 4) {
                            holder.tvName.setText("医养管家【" + chatInfo.getChatName() + "】");
                            MessageHeaderHelper.setHeader(mContext, holder.rlHeaders, R.mipmap.icon_medical_housekeeper_header);
                        } else {
                            holder.tvName.setText(chatInfo.getChatName());
                            holder.setHeadrs(mContext, chatInfo.getHeadersJson());
                        }

                        holder.llSwipeMenuRoot.removeAllViews();

                        int padding = SizeUtils.dp2px(12);

                        TextView tvNoDisturb = new TextView(mContext);
                        tvNoDisturb.setText(chatInfo.isNoDisturb() ? "取消\n免打扰" : "消息\n免打扰");
                        tvNoDisturb.setTextAppearance(R.style.NormalTextView);
                        tvNoDisturb.setBackgroundColor(Color.parseColor("#E5E5E5"));
                        tvNoDisturb.setPadding(padding, 0, padding, 0);
                        tvNoDisturb.setGravity(Gravity.CENTER);
                        tvNoDisturb.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        tvNoDisturb.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                RequestManager requestManager = RequestManager.getInstance();
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", chat.getRecipientId());
                                params.put("no_disturb", !chatInfo.isNoDisturb());
                                BaseObserverImpl<Object> observer = new BaseObserverImpl<Object>(mContext) {
                                    @Override
                                    public void onSuccess() {
                                        super.onSuccess();
                                        ChatInfo chatInfo = chat.getChatInfo();
                                        chatInfo.setNoDisturb(!chatInfo.isNoDisturb());
                                        MessageManager.save(chatInfo);
                                        notifyItemChanged(position);
                                    }
                                };
                                if (chatType == ChatType.GROUP_CHAT) {
                                    requestManager.request(requestManager.mMessageRetrofitService.editGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                                            observer);
                                } else if (chatType == ChatType.PRIVATE_CHAT) {
                                    requestManager.request(requestManager.mMessageRetrofitService.editContactUser(RequestManager.getJsonRequestBody(params)),
                                            observer);
                                }

                                callback.noDisturb(chat);
                            }
                        });
                        holder.llSwipeMenuRoot.addView(tvNoDisturb);

                        TextView tvTopping = new TextView(mContext);
                        tvTopping.setText(chatInfo.isTopping() ? "取消\n置顶" : "置顶");
                        tvTopping.setTextAppearance(R.style.NormalTextView);
                        tvTopping.setTextColor(Color.WHITE);
                        tvTopping.setBackgroundColor(Color.parseColor("#6E90FF"));
                        tvTopping.setPadding(padding, 0, padding, 0);
                        tvTopping.setGravity(Gravity.CENTER);
                        tvTopping.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        tvTopping.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                BaseObserverImpl<Object> observer = new BaseObserverImpl<Object>(mContext) {
                                    @Override
                                    public void onSuccess() {
                                        super.onSuccess();
                                        ChatInfo chatInfo = chat.getChatInfo();
                                        chatInfo.setTopping(!chatInfo.isTopping());

                                        if (chatInfo.isTopping()) {
                                            chat.setToppingTime(System.currentTimeMillis());
                                        } else {
                                            chat.setToppingTime(0);
                                        }
                                        chat.setChatInfo(chatInfo);
                                        MessageManager.setChatTopping(chat);

                                        callback.topping(chat);
                                    }
                                };

                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", chat.getRecipientId());
                                params.put("is_stick", !chat.getChatInfo().isTopping());

                                RequestManager requestManager = RequestManager.getInstance();
                                switch (chatType) {
                                    case GROUP_CHAT:
                                        requestManager.request(requestManager.mMessageRetrofitService
                                                .editGroupChatSetting(RequestManager.getJsonRequestBody(params)), observer);
                                        break;
                                    case PRIVATE_CHAT:
                                        params.put("is_stick", !chat.getChatInfo().isTopping());
                                        requestManager.request(requestManager.mMessageRetrofitService
                                                .editContactUser(RequestManager.getJsonRequestBody(params)), observer);
                                        break;
                                }
                                callback.topping(chat);
                            }
                        });
                        holder.llSwipeMenuRoot.addView(tvTopping);

                        TextView tvDelete = new TextView(mContext);
                        tvDelete.setText("删除");
                        tvDelete.setTextAppearance(R.style.NormalTextView);
                        tvDelete.setTextColor(Color.WHITE);
                        tvDelete.setBackgroundColor(Color.parseColor("#FF6E73"));
                        tvDelete.setPadding(padding, 0, padding, 0);
                        tvDelete.setGravity(Gravity.CENTER);
                        tvDelete.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        tvDelete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogHelper.showNormalDialog(mContext, "确定要删除该聊天吗？",
                                        new DialogHelper.Callback() {
                                            @Override
                                            public void onRightClick(AlertDialog alertDialog) {
                                                super.onRightClick(alertDialog);

                                                MessageManager.deleteChat(chat.getChatId());
//                                                    remove(position);
                                                callback.delete(chat);
                                            }
                                        });
                            }
                        });
                        holder.llSwipeMenuRoot.addView(tvDelete);

                        if (chatInfo.isNoDisturb()) {
                            holder.ivNoDisturb.setVisibility(View.VISIBLE);
                        }

                        if (holder.tvUnreadCount.getVisibility() == View.VISIBLE) {
                            ViewGroup.LayoutParams layoutParams = holder.tvUnreadCount.getLayoutParams();
                            if (chatInfo.isNoDisturb()) {
                                holder.tvUnreadCount.setText("");
                                layoutParams.width = SizeUtils.dp2px(5);
                                layoutParams.height = SizeUtils.dp2px(5);
                            } else {
                                layoutParams.width = SizeUtils.dp2px(20);
                                layoutParams.height = SizeUtils.dp2px(20);
                            }
                            holder.tvUnreadCount.setLayoutParams(layoutParams);
                        }
                    }

                    break;
                default:
                    holder.swipeMenuLayout.setSwipeEnable(false);
                    holder.tvName.setText(chatType.getName());
                    MessageHeaderHelper.setHeader(mContext, holder.rlHeaders, chatType.getHeader());
                    if (chatMessage != null) {
                        if (!TextUtils.isEmpty(chatMessage.getContent())) {
                            switch (chatType) {
                                case VERIFICATION:
                                case STRANGER:
                                    holder.tvContent.setText(chatMessage.getUsername() + "：" + chatMessage.getContent());
                                    break;
                                default:
                                    holder.tvContent.setText(chatMessage.getContent());
                                    break;
                            }
                        }
                    }
                    break;
            }

            holder.rlRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onItemClick(chat);
                }
            });

            if (chatMessage != null) {
                long time = chatMessage.getTime();

                if (time > 0) {
                    holder.tvTime.setVisibility(View.VISIBLE);
                    Date date = new Date(time);
                    if (TimeUtils.isToday(time)) {
                        holder.tvTime.setText(sdf.format(date));
                    } else {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(System.currentTimeMillis());
                        int x = calendar.get(Calendar.DAY_OF_YEAR);

                        calendar.setTimeInMillis(time);
                        int y = calendar.get(Calendar.DAY_OF_YEAR);

                        if (x - y == 1) {
                            holder.tvTime.setText("昨天 " + sdf.format(date));
                        } else {
                            holder.tvTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date));
                        }
                    }
                }
            }
        }
    }

    public interface Callback {
        void onItemClick(Chat chat);

        void topping(Chat chat);

        void delete(Chat chat);

        void noDisturb(Chat chat);
    }

    public static class ViewHolder extends BaseNormalListAdapter.ViewHolder {
        RelativeLayout rlRoot;
        RelativeLayout rlHeaders;
        TextView tvTime;
        TextView tvContent;
        TextView tvName;
        ImageView ivSendFailure;
        ImageView ivNoDisturb;

        TextView tvUnreadCount;

        SwipeMenuLayout swipeMenuLayout;
        LinearLayout llSwipeMenuRoot;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            swipeMenuLayout = itemView.findViewById(R.id.swipe_menu_layout);
            llSwipeMenuRoot = itemView.findViewById(R.id.ll_swipe_menu_root);
            rlRoot = itemView.findViewById(R.id.rl_root);
            rlHeaders = itemView.findViewById(R.id.rl_headers);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvContent = itemView.findViewById(R.id.tv_content);
            tvName = itemView.findViewById(R.id.tv_name);
            ivSendFailure = itemView.findViewById(R.id.iv_send_failure);
            tvUnreadCount = itemView.findViewById(R.id.tv_unread_count);
            ivNoDisturb = itemView.findViewById(R.id.iv_no_disturb);
        }

        public void setHeadrs(Context context, String headersJson) {
            if (TextUtils.isEmpty(headersJson)) {
                MessageHeaderHelper.setHeader(context, rlHeaders, R.mipmap.icon_default_header_man);
            } else {
                ArrayList<String> headers = new Gson().fromJson(headersJson, new TypeToken<ArrayList<String>>() {
                }.getType());
                if (headers == null) {
                    headers = new ArrayList<>();
                }
                MessageHeaderHelper.setHeader(context, rlHeaders, headers);
            }
        }
    }
}
















